package com.taylor.community.controller;

import com.alibaba.fastjson.JSONObject;
import com.taylor.community.entity.Message;
import com.taylor.community.entity.Page;
import com.taylor.community.entity.User;
import com.taylor.community.service.MessageService;
import com.taylor.community.service.UserService;
import com.taylor.community.util.CommunityConstant;
import com.taylor.community.util.CommunityUtil;
import com.taylor.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

import java.lang.reflect.Array;
import java.util.*;

@Controller
public class MessageController implements CommunityConstant{
    @Autowired
    private MessageService messageService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private UserService userService;
    //会话数量
    @RequestMapping(path = "/letter/list",method = RequestMethod.GET)
    public String getLetterList(Model model, Page page){
        User user = hostHolder.getUser();
        page.setLimit(5);
        page.setPath("/letter/list");
        page.setRows(messageService.findConversationCount(user.getId()));
        List<Message> conversationList = messageService.findConversations(user.getId(),
                page.getOffset(),page.getLimit());
        List<Map<String,Object>> conversations = new ArrayList<>();
        if(true) {
            return null;
        }
        if(conversationList != null){
            for(Message message : conversationList){
                Map<String,Object> map = new HashMap<>();
                map.put("conversation",message);
                map.put("letterCount",messageService.findLetterCount(message.getConversationId()));
                //每个会话的私信未读数量
                map.put("unreadCount",messageService.findLetterUnReadCount(user.getId(),message.getConversationId()));
                //会话列表 每个会话最近一条的接收者
                int targetId = user.getId() == message.getFromId() ? message.getToId() : message.getFromId();
                map.put("target",userService.findUserById(targetId));
                conversations.add(map);
            }
        }
        model.addAttribute("conversations",conversations);
        //用户未读消息总数
        int letterUnReadCount = messageService.findLetterUnReadCount(user.getId(),null);
        model.addAttribute("letterUnreadCount",letterUnReadCount);
        //用户未读系统通知
        int noticeUnreadCount = messageService.findUnreadNoticeCount(user.getId(),null);
        model.addAttribute("noticeUnreadCount",noticeUnreadCount);
        return "/site/letter";
    }

    /**
     * 会话详情页
     * @param conversationId
     * @param page
     * @param model
     * @return
     */
    @RequestMapping(path = "/letter/detail/{conversationId}",method = RequestMethod.GET)
    public String getLetterDetail(@PathVariable("conversationId")String conversationId,Page page,Model model){
        page.setLimit(5);
        page.setPath("/letter/detail/"+conversationId);
        page.setRows(messageService.findLetterCount(conversationId));
        //每个会话详情的列表 即两个用户之间的对话
        List<Message> letterList = messageService.findLetters(conversationId,page.getOffset(),page.getLimit());
        List<Map<String,Object>> letters = new ArrayList<>();
        if(letterList != null){
            for (Message message : letterList){
                Map<String,Object> map = new HashMap<>();
                map.put("letter",message);
                map.put("fromUser",userService.findUserById(message.getFromId()));
                letters.add(map);
            }
        }
        model.addAttribute("letters",letters);
        //私信目标
        model.addAttribute("target",getLetterTarget(conversationId));
        //设置已读
        List<Integer> ids = getLetterIds(letterList);
        if(!ids.isEmpty()){
            messageService.readMessage(ids);
        }
        return "/site/letter-detail";
    }

    /**
     * 某一个会话的下的对话 from_id和to_id组合有两种情况 通过当前登录的用户来判断谁是通信对象
     * @param conversationId
     * @return
     */
    private User getLetterTarget(String conversationId){
        String[] ids = conversationId.split("_");
        int id0 = Integer.parseInt(ids[0]);
        int id1 = Integer.parseInt(ids[1]);
        if(hostHolder.getUser().getId() == id0){
            return userService.findUserById(id1);
        }
        else {
            return userService.findUserById(id0);
        }
    }

    /**
     * 从用户的会话详情页面中 获取每个会话的私信列表
     * @param letterList
     * @return 封装私信id的列表
     */

    private List<Integer> getLetterIds(List<Message> letterList){
        List<Integer> ids = new ArrayList<>();
        if(letterList != null){
            for(Message message : letterList){
                if(hostHolder.getUser().getId() == message.getToId() && message.getStatus() == 0){
                    ids.add(message.getId());
                }
            }
        }
        return ids;
    }
    /**
     * 发送私信
     * @param toName
     * @param content
     * @return
     */
    @RequestMapping(path = "/letter/send",method = RequestMethod.POST)
    @ResponseBody//处理Ajax异步请求 返回JSON格式数据
    public String sendLetter(String toName,String content){
        User target = userService.findUserByName(toName);
        if(target == null){
            return CommunityUtil.getJSONString(500,"目标用户不存在");
        }
        Message message = new Message();
        message.setFromId(hostHolder.getUser().getId());
        message.setToId(target.getId());
        if(message.getFromId() > message.getToId()){
            message.setConversationId(message.getToId() + "_" +message.getFromId());
        }
        else {
            message.setConversationId(message.getFromId() + "_" + message.getToId());
        }
        message.setContent(content);
        message.setCreateTime(new Date());
        messageService.addMessage(message);
        return CommunityUtil.getJSONString(200);
    }

    /**
     * 删除私信
     * @param id
     * @return
     */
    @RequestMapping(path = "/letter/delete",method = RequestMethod.POST)
    @ResponseBody
    public String deleteLetter(int id){
        messageService.deleteMessage(id);
        return CommunityUtil.getJSONString(200,"无法删除！");
    }

    /**
     * 查询不同类型系统最新通知 当页列表只显示最新的通知的信息
     * @param model
     * @return
     */
    @RequestMapping(path = "/notice/list",method = RequestMethod.GET)
    public String getNoticeList(Model model){
        User user = hostHolder.getUser();
        getTopicNotice(user,TOPIC_COMMENT,model);
        getTopicNotice(user,TOPIC_LIKE,model);
        getTopicNotice(user,TOPIC_FOLLOW,model);
        //查询私信未读数量
        int letterUnreadCount = messageService.findLetterUnReadCount(user.getId(),null);
        model.addAttribute("letterUnreadCount",letterUnreadCount);
        //查询系统通知未读数量
        int noticeUnreadCount = messageService.findUnreadNoticeCount(user.getId(),null);
        model.addAttribute("noticeUnreadCount",noticeUnreadCount);
        return "/site/notice";

    }

    /**
     * 查询不同类型系统最新通知辅助方法 查询每类最新的通知的相关数据
     * @param user
     * @param topic
     * @return
     */
    private void getTopicNotice(User user,String topic,Model model){
        Message message = messageService.findLatestNotice(user.getId(),topic);
        if(message != null){
            Map<String,Object> messageVo = new HashMap<>();
            messageVo.put("message",message);
            //message表中的content经过转义存进去 需要转回对象
            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String,Object> data = JSONObject.parseObject(content,HashMap.class);
            messageVo.put("user",userService.findUserById((Integer) data.get("userId")));
            messageVo.put("entityType",data.get("entityType"));
            messageVo.put("entityId",data.get("entityId"));
            if(topic != "follow"){
                messageVo.put("postId",data.get("postId"));
            }
            //评论类通知的数量
            int count = messageService.findNoticeCount(user.getId(),topic);
            messageVo.put("count",count);
            int unread = messageService.findUnreadNoticeCount(user.getId(),topic);
            messageVo.put("unread",unread);
            model.addAttribute(topic + "Notice",messageVo);
        }
    }

    /**
     * 从系统通知列表进入某主题的会话详情页
     * @param topic
     * @param page
     * @param model
     * @return
     */
    @RequestMapping(path = "/notice/detail/{topic}" ,method = RequestMethod.GET)
    public String getNoticesDetail(@PathVariable("topic")String topic,Page page,Model model){
        User user = hostHolder.getUser();
        page.setPath("/notice/detail/"+topic);
        page.setLimit(5);
        page.setRows(messageService.findNoticeCount(user.getId(),topic));
        List<Message> noticeList = messageService.findNotices(user.getId(),topic,page.getOffset(),page.getLimit());
        List<Map<String ,Object>> noticeVoList = new ArrayList<>();
        for(Message notice : noticeList){
            Map<String,Object> map = new HashMap<>();
            map.put("notice",notice);
            //将数据库存到内容转化为字符串 再转化为对象
            String content = HtmlUtils.htmlUnescape(notice.getContent());
            Map<String,Object> data = JSONObject.parseObject(content);
            map.put("user",userService.findUserById((Integer) data.get("userId")));
            map.put("entityType",data.get("entityType"));
            map.put("entityId",data.get("entityId"));
            map.put("postId",data.get("postId"));
            map.put("fromUser",userService.findUserById(notice.getFromId()));
            noticeVoList.add(map);
        }
        model.addAttribute("notices",noticeVoList);
        //设置已读
        List<Integer> ids =getLetterIds(noticeList);
        if(!ids.isEmpty()){
            messageService.readMessage(ids);
        }
        return "/site/notice-detail";
    }

}
